<template>
  <div class="dashboard">
    <el-container>
      <!-- 头部 -->
      <el-header class="header">
        <div class="header-left">
          <el-icon :size="24" color="#1f4e79">
            <Van />
          </el-icon>
          <span class="title">环海运通管理系统</span>
        </div>
        <div class="header-right">
          <el-dropdown trigger="click">
            <span class="user-info">
              <el-avatar :size="32" :src="userAvatarUrl">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span class="username">{{ authStore.user?.email || '用户' }}</span>
              <el-icon class="arrow"><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="goToProfile">
                  <el-icon><User /></el-icon>
                  个人资料
                </el-dropdown-item>
                <el-dropdown-item divided @click="handleLogout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 主体内容 -->
      <el-main class="main">
        <div class="welcome-card">
          <div class="welcome-content">
            <h1>欢迎来到环海运通管理系统！</h1>
            <p>您已成功登录，现在可以开始使用我们的专业国际物流运输管理平台。</p>

            <!-- 消息通知区域 -->
            <MessageNotification 
              v-if="
                authStore.user?.is_superuser ||
                permissionStore.hasPermission('system.message.list')
              "
              ref="messageNotificationRef"
              class="message-section"
            />

            <!-- 快捷查询区域 -->
            <div 
              v-if="
                authStore.user?.is_superuser ||
                permissionStore.hasPermission('vessel_schedule_list')
              "
              class="quick-search-section"
            >
              <el-card class="quick-search-card" shadow="hover">
                <template #header>
                  <div class="search-header">
                    <el-icon class="search-icon"><Ship /></el-icon>
                    <span class="search-title">快速船期查询</span>
                  </div>
                </template>
                
                <div class="search-form">
                  <div class="form-row">
                    <div class="form-item">
                      <label class="form-label">起运港</label>
                      <el-select
                        v-model="selectedCity"
                        placeholder="选择起运港"
                        filterable
                        remote
                        clearable
                        :remote-method="handlePolSearch"
                        @change="handlePolSelect"
                        style="width: 100%"
                      >
                        <el-option
                          v-for="port in polPortOptions"
                          :key="port.code"
                          :label="port.name"
                          :value="port.code"
                        />
                      </el-select>
                    </div>
                    
                    <div class="form-item">
                      <label class="form-label">目的港</label>
                      <el-select
                        v-model="quickQueryForm.podCd"
                        placeholder="选择目的港"
                        filterable
                        remote
                        clearable
                        :remote-method="handlePodSearch"
                        style="width: 100%"
                      >
                        <el-option
                          v-for="port in podPortOptions"
                          :key="port.code"
                          :label="port.name"
                          :value="port.code"
                        />
                      </el-select>
                    </div>
                    
                    <div class="form-item">
                      <el-button 
                        type="primary" 
                        size="large"
                        @click="handleQuickSearch"
                        :disabled="!quickQueryForm.polCd || !quickQueryForm.podCd"
                        class="search-btn"
                      >
                        <el-icon><Search /></el-icon>
                        立即查询
                      </el-button>
                    </div>
                  </div>
                </div>
                
                <!-- 常用航线 -->
                <div class="quick-routes">
                  <div class="routes-header">
                    <span class="routes-title">🔥 热门航线</span>
                  </div>
                  <div class="routes-list">
                    <div
                      v-for="route in quickRoutes"
                      :key="`${route.polCd}-${route.podCd}`"
                      class="route-item"
                    >
                      <el-button
                        class="route-btn"
                        size="small"
                        @click="selectQuickRoute(route)"
                        :title="getRouteTooltip(route)"
                      >
                        <div class="route-content">
                          <span class="route-name">{{ route.name }}</span>
                          <span v-if="route.isPopular && route.searchCount > 0" class="route-stats">
                            🔍 {{ route.searchCount }}
                          </span>
                          <span v-else-if="route.isFavorite" class="route-stats">
                            ⭐ 已收藏
                          </span>
                        </div>
                      </el-button>
                      <el-button
                        class="favorite-btn"
                        size="small"
                        :type="route.isFavorite ? 'warning' : 'default'"
                        circle
                        @click="handleFavoriteClick(route, $event)"
                        :title="route.isFavorite ? '取消收藏' : '收藏航线'"
                      >
                        <el-icon>
                          <StarFilled v-if="route.isFavorite" />
                          <Star v-else />
                        </el-icon>
                      </el-button>
                    </div>
                  </div>
                </div>
              </el-card>
            </div>

            <div class="feature-grid">
              <!-- 船期管理功能 -->
              <div
                v-if="
                  authStore.user?.is_superuser ||
                  permissionStore.hasPermission('vessel_schedule_list')
                "
                class="feature-card"
                @click="navigateToFeature('shipping')"
              >
                <div class="feature-icon shipping">
                  <el-icon :size="32"><Van /></el-icon>
                </div>
                <h3>船期管理</h3>
                <p>查看和管理船期信息，跟踪货物运输状态</p>
              </div>

              <!-- 系统管理功能 -->
              <div
                v-if="shouldShowAdminFeature"
                class="feature-card admin"
                @click="navigateToFeature('admin')"
              >
                <div class="feature-icon admin">
                  <el-icon :size="32"><Setting /></el-icon>
                </div>
                <h3>系统管理</h3>
                <p>用户管理、角色分配、权限配置、本地费用管理</p>
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { computed, ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { usePermissionStore } from '@/stores/permission'
import { Van, User, ArrowDown, SwitchButton, Setting, Search, Ship, Star, StarFilled } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { getUserAvatarUrl } from '@/utils/avatar'
import { chineseCityPorts, searchPorts } from '@/data/ports'
import request from '@/api/request'
import MessageNotification from '@/components/MessageNotification.vue'

const router = useRouter()
const authStore = useAuthStore()
const permissionStore = usePermissionStore()

// 计算头像URL
const userAvatarUrl = computed(() => {
  // 在开发环境中，使用空字符串让浏览器通过 Vite 代理访问
  // 在生产环境中，使用环境变量配置的后端服务器地址
  const baseURL = import.meta.env.DEV ? '' : (import.meta.env.VITE_API_URL || '')
  return getUserAvatarUrl(authStore.user, baseURL, authStore.avatarVersion)
})

// 处理登出
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await authStore.logout()
    router.push('/login')
  } catch {
    // 用户取消操作
  }
}

// 跳转到个人资料页面
const goToProfile = () => {
  router.push('/profile')
}

// 判断是否显示系统管理功能
const shouldShowAdminFeature = computed(() => {
  // 超级管理员和工作人员始终显示
  if (authStore.user?.is_superuser || authStore.user?.is_staff) {
    return true
  }
  
  // 检查用户是否拥有任何管理相关权限
  const adminPermissions = [
    'user.list', 'user.detail', 'user.create', 'user.update', 'user.delete',
    'role.list', 'role.detail', 'role.create', 'role.update', 'role.delete', 
    'permission.list', 'permission.detail',
    'local_fee.list', 'local_fee.detail', 'local_fee.create', 'local_fee.update', 'local_fee.delete'
  ]
  
  return authStore.hasAnyPermission(adminPermissions)
})

// 导航到功能页面
const navigateToFeature = feature => {
  switch (feature) {
    case 'admin':
      router.push('/management')
      break
    case 'shipping':
      router.push('/schedule')
      break
  }
}

// === 快捷查询功能 ===
// 快捷查询表单数据
const quickQueryForm = reactive({
  polCd: 'SHENZHEN', // 默认深圳（城市）
  podCd: ''
})

// 港口搜索值
const polSearchValue = ref('')
const podSearchValue = ref('')

// 当前选中的城市（用于起运港下拉框显示）
const selectedCity = ref('')

// 用户收藏航线数据
const userFavoriteRoutes = ref([])
const loadingRoutes = ref(false)

// 热门航线数据（基于搜索频次）
const popularRoutes = ref([])
const loadingPopularRoutes = ref(false)

// 计算显示的航线（优先显示用户收藏，不足时补充热门航线）
const quickRoutes = computed(() => {
  const favoriteRoutes = userFavoriteRoutes.value.map(route => ({
    polCd: route.polCd,
    podCd: route.podCd,
    name: route.name,
    isFavorite: true,
    id: route.id,
    isPopular: false
  }))
  
  // 如果收藏航线少于6条，用热门航线补充
  if (favoriteRoutes.length < 6) {
    const usedRoutes = new Set(favoriteRoutes.map(r => `${r.polCd}-${r.podCd}`))
    const additionalRoutes = popularRoutes.value.filter(route => 
      !usedRoutes.has(`${route.polCd}-${route.podCd}`)
    ).slice(0, 6 - favoriteRoutes.length).map(route => ({
      polCd: route.polCd,
      podCd: route.podCd,
      name: route.name,
      isFavorite: false,
      isPopular: true,
      searchCount: route.searchCount,
      popularityScore: route.popularityScore
    }))
    
    return [...favoriteRoutes, ...additionalRoutes]
  }
  
  return favoriteRoutes.slice(0, 6)
})

// 计算属性 - 港口选项
const polPortOptions = computed(() => {
  if (!polSearchValue.value) {
    return chineseCityPorts
  }
  return searchPorts(polSearchValue.value).slice(0, 20) // 限制显示数量
})

const podPortOptions = computed(() => {
  if (!podSearchValue.value) {
    // 当没有搜索值时，显示所有港口的前50个（包含常用目的港）
    return searchPorts('').slice(0, 50)
  }
  return searchPorts(podSearchValue.value).slice(0, 20)
})

// 获取港口名称
const getPortName = code => {
  const allPorts = searchPorts('')
  const port = allPorts.find(p => p.code === code)
  return port ? port.name : code
}

// 获取航线提示信息
const getRouteTooltip = route => {
  if (route.isFavorite) {
    return `⭐ 已收藏的航线：${route.name}`
  } else if (route.isPopular && route.searchCount > 0) {
    let tooltip = `🔥 热门航线：${route.name}\n🔍 搜索次数：${route.searchCount}`
    if (route.popularityScore > 0) {
      tooltip += `\n📊 热度评分：${route.popularityScore}`
    }
    return tooltip
  } else if (route.isDefault) {
    return `📍 常用航线：${route.name}`
  }
  return route.name
}

// 处理起运港搜索
const handlePolSearch = searchValue => {
  polSearchValue.value = searchValue
}

// 处理目的港搜索  
const handlePodSearch = searchValue => {
  podSearchValue.value = searchValue
}

// 处理起运港选择
const handlePolSelect = portCode => {
  if (!portCode) {
    selectedCity.value = ''
    quickQueryForm.polCd = ''
    return
  }
  
  selectedCity.value = portCode
  
  // 检查是否是中国城市港口
  const city = chineseCityPorts.find(c => c.code === portCode)
  if (city && city.terminals && city.terminals.length > 0) {
    // 是中国城市，默认选择第一个码头
    quickQueryForm.polCd = city.terminals[0].code
  } else {
    // 是具体港口，直接使用
    quickQueryForm.polCd = portCode
  }
}

// 快速选择航线
const selectQuickRoute = route => {
  // 处理起运港：查找对应的城市代码用于显示
  const polCd = route.polCd
  let cityCode = polCd
  
  // 查找是否是中国城市港口的码头
  for (const city of chineseCityPorts) {
    if (city.terminals && city.terminals.some(terminal => terminal.code === polCd)) {
      cityCode = city.code  // 找到对应的城市代码
      break
    }
  }
  
  // 查找目的港名称，确保在选项中
  const podCd = route.podCd
  const allPorts = searchPorts('')
  const podPort = allPorts.find(port => port.code === podCd)
  
  // 更新表单数据：起运港显示城市，目的港显示港口代码
  selectedCity.value = cityCode
  quickQueryForm.polCd = polCd  // 实际查询用具体港口代码
  quickQueryForm.podCd = podCd  // 目的港使用港口代码
  
  // 设置目的港搜索值，确保对应选项出现（使用港口名称的一部分）
  if (podPort) {
    // 使用港口名称的第一部分作为搜索关键词，这样下拉框会显示包含该港口的选项
    const nameMatch = podPort.name.match(/^([A-Z\s]+)/);
    if (nameMatch) {
      podSearchValue.value = nameMatch[1].trim();
    }
  }
  
  ElMessage.success(`已选择航线: ${route.name}`)
}

// 执行快捷查询
const handleQuickSearch = () => {
  if (!quickQueryForm.polCd || !quickQueryForm.podCd) {
    ElMessage.warning('请选择起运港和目的港')
    return
  }
  
  if (quickQueryForm.polCd === quickQueryForm.podCd) {
    ElMessage.warning('起运港和目的港不能相同')
    return
  }
  
  // 处理起运港：如果是城市代码，转换为具体港口代码
  let finalPolCd = quickQueryForm.polCd
  const city = chineseCityPorts.find(c => c.code === quickQueryForm.polCd)
  if (city && city.terminals && city.terminals.length > 0) {
    // 是城市代码，使用第一个码头
    finalPolCd = city.terminals[0].code
  }
  
  // 跳转到船期查询页面并传递参数
  router.push({
    path: '/schedule',
    query: {
      polCd: finalPolCd,
      podCd: quickQueryForm.podCd,
      autoSearch: 'true'
    }
  })
  
  ElMessage.success('正在为您查询船期信息...')
}

// === 收藏航线功能 ===
// 获取用户收藏航线
const fetchUserFavoriteRoutes = async () => {
  try {
    loadingRoutes.value = true
    const response = await request.get('/auth/me/favorite-routes/')
    
    if (response.data.success) {
      userFavoriteRoutes.value = response.data.data.routes
    } else {
      console.warn('获取收藏航线失败:', response.data.message)
    }
  } catch (error) {
    console.warn('获取收藏航线失败:', error)
    // 失败时不显示错误信息，静默降级到热门航线
  } finally {
    loadingRoutes.value = false
  }
}

// 获取热门航线（基于搜索频次）
const fetchPopularRoutes = async () => {
  try {
    loadingPopularRoutes.value = true
    const response = await request.get('/popular-routes/?limit=10')
    
    if (response.data.success) {
      popularRoutes.value = response.data.data.routes
      console.log('获取热门航线成功:', popularRoutes.value.length, '条')
    } else {
      console.warn('获取热门航线失败:', response.data.message)
      // 失败时使用默认的降级数据
      popularRoutes.value = [
        { polCd: 'CNSHK', podCd: 'INMAA', name: '蛇口 → 金奈', searchCount: 0, isDefault: true },
        { polCd: 'CNDCB', podCd: 'SGSIN', name: '大铲湾 → 新加坡', searchCount: 0, isDefault: true },
        { polCd: 'CNYTN', podCd: 'IDJKT', name: '盐田 → 雅加达', searchCount: 0, isDefault: true },
        { polCd: 'CNSHK', podCd: 'VNHPH', name: '蛇口 → 海防', searchCount: 0, isDefault: true },
        { polCd: 'CNNAN', podCd: 'THBKK', name: '广州南沙 → 曼谷', searchCount: 0, isDefault: true },
        { polCd: 'CNDCB', podCd: 'VNSGN', name: '大铲湾 → 胡志明', searchCount: 0, isDefault: true }
      ]
    }
  } catch (error) {
    console.warn('获取热门航线失败:', error)
    // 网络错误时使用默认降级数据
    popularRoutes.value = [
      { polCd: 'CNSHK', podCd: 'INMAA', name: '蛇口 → 金奈', searchCount: 0, isDefault: true },
      { polCd: 'CNDCB', podCd: 'SGSIN', name: '大铲湾 → 新加坡', searchCount: 0, isDefault: true },
      { polCd: 'CNYTN', podCd: 'IDJKT', name: '盐田 → 雅加达', searchCount: 0, isDefault: true },
      { polCd: 'CNSHK', podCd: 'VNHPH', name: '蛇口 → 海防', searchCount: 0, isDefault: true },
      { polCd: 'CNNAN', podCd: 'THBKK', name: '广州南沙 → 曼谷', searchCount: 0, isDefault: true },
      { polCd: 'CNDCB', podCd: 'VNSGN', name: '大铲湾 → 胡志明', searchCount: 0, isDefault: true }
    ]
  } finally {
    loadingPopularRoutes.value = false
  }
}

// 添加收藏航线
const addFavoriteRoute = async (route) => {
  try {
    const response = await request.post('/auth/me/favorite-routes/add/', {
      polCd: route.polCd,
      podCd: route.podCd,
      name: route.name
    })
    
    if (response.data.success) {
      // 更新本地收藏列表
      userFavoriteRoutes.value.push(response.data.data.route)
      ElMessage.success(`已收藏航线: ${route.name}`)
    } else {
      ElMessage.warning(response.data.message || '收藏失败')
    }
  } catch (error) {
    console.error('添加收藏失败:', error)
    ElMessage.error('收藏航线失败')
  }
}

// 取消收藏航线
const removeFavoriteRoute = async (routeId, routeName) => {
  try {
    const response = await request.delete(`/auth/me/favorite-routes/${routeId}/remove/`)
    
    if (response.data.success) {
      // 从本地收藏列表中移除
      userFavoriteRoutes.value = userFavoriteRoutes.value.filter(r => r.id !== routeId)
      ElMessage.success(`已取消收藏: ${routeName}`)
    } else {
      ElMessage.warning(response.data.message || '取消收藏失败')
    }
  } catch (error) {
    console.error('取消收藏失败:', error)
    ElMessage.error('取消收藏失败')
  }
}

// 处理收藏按钮点击
const handleFavoriteClick = async (route, event) => {
  event.stopPropagation() // 阻止冒泡到路线选择事件
  
  if (route.isFavorite) {
    await removeFavoriteRoute(route.id, route.name)
  } else {
    await addFavoriteRoute(route)
  }
}

// 消息通知组件引用
const messageNotificationRef = ref(null)

// 组件挂载时获取数据
onMounted(async () => {
  // 调试权限信息
  console.log('=== Dashboard 权限调试信息 ===')
  console.log('当前用户:', authStore.user)
  console.log('是否超级用户:', authStore.user?.is_superuser)
  console.log('权限store状态:', {
    permissionsLoaded: permissionStore.permissionsLoaded,
    userPermissions: permissionStore.userPermissions
  })
  console.log('检查vessel_schedule_list权限:', permissionStore.hasPermission('vessel_schedule_list'))
  console.log('========================')
  
  // 初始化默认选中城市
  selectedCity.value = 'SHENZHEN'
  
  // 先获取热门航线（对所有用户可见）
  await fetchPopularRoutes()
  
  // 只有登录用户才获取收藏航线
  if (authStore.user) {
    await fetchUserFavoriteRoutes()
  }
})
</script>

<style lang="scss" scoped>
.dashboard {
  width: 100%;
  height: 100vh;
  background: #f5f5f5;
}

.header {
  background: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .header-left {
    display: flex;
    align-items: center;
    gap: 12px;

    .title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }

  .header-right {
    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 8px 12px;
      border-radius: 8px;
      cursor: pointer;
      transition: background 0.3s ease;

      &:hover {
        background: #f5f5f5;
      }

      .username {
        font-size: 14px;
        color: #333;
      }

      .arrow {
        font-size: 12px;
        color: #666;
      }
    }
  }
}

.main {
  padding: 24px;
  overflow-y: auto;
  height: calc(100vh - 60px); /* 减去header高度 */
}

.welcome-card {
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  animation: slideIn 0.6s ease-out;

  .welcome-content {
    text-align: center;

    h1 {
      font-size: 32px;
      font-weight: 600;
      color: #333;
      margin-bottom: 16px;
      background: linear-gradient(135deg, #1f4e79, #2c5aa0);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }

    p {
      font-size: 16px;
      color: #666;
      margin-bottom: 48px;
      line-height: 1.6;
    }

    .feature-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
      gap: 24px;
      margin-top: 48px;

      .feature-card {
        text-align: center;
        padding: 32px 24px;
        border-radius: 16px;
        background: #f8f9fa;
        transition: all 0.3s ease;
        cursor: pointer;
        border: 2px solid transparent;

        &:hover {
          transform: translateY(-4px);
          box-shadow: 0 12px 32px rgba(0, 0, 0, 0.12);
          border-color: #409eff;
        }

        .feature-icon {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 64px;
          height: 64px;
          margin: 0 auto 20px;
          border-radius: 16px;

          &.shipping {
            background: linear-gradient(135deg, #1f4e79, #2c5aa0);
            color: white;
          }

          &.admin {
            background: linear-gradient(135deg, #f56c6c, #f78989);
            color: white;
          }
        }

        h3 {
          font-size: 18px;
          font-weight: 600;
          color: #333;
          margin-bottom: 12px;
        }

        p {
          font-size: 14px;
          color: #666;
          line-height: 1.5;
          margin: 0;
        }
      }
    }
  }
}

// 动画
@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .header {
    padding: 0 16px;

    .header-left .title {
      display: none;
    }
  }

  .main {
    padding: 16px;
  }

  .welcome-card {
    padding: 24px 16px;

    .welcome-content {
      h1 {
        font-size: 24px;
      }

      .feature-grid {
        grid-template-columns: 1fr;
        gap: 16px;
        margin-top: 32px;
      }
    }
  }
}

/* === 消息通知区域样式 === */
.message-section {
  margin: 32px 0;
  animation: fadeIn 0.6s ease-out 0.2s both;
}

/* === 快捷查询区域样式 === */
.quick-search-section {
  margin: 32px 0;
  
  .quick-search-card {
    background: linear-gradient(135deg, #f8fafe 0%, #f0f6ff 100%);
    border: 1px solid #e1ebf7;
    border-radius: 16px;
    overflow: hidden;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 32px rgba(31, 78, 121, 0.12);
    }
    
    :deep(.el-card__header) {
      background: linear-gradient(135deg, #1f4e79 0%, #2c5aa0 100%);
      border-bottom: none;
      padding: 16px 20px;
      
      .search-header {
        display: flex;
        align-items: center;
        gap: 10px;
        color: white;
        
        .search-icon {
          font-size: 20px;
        }
        
        .search-title {
          font-size: 16px;
          font-weight: 600;
        }
      }
    }
    
    :deep(.el-card__body) {
      padding: 24px;
    }
  }
}

.search-form {
  .form-row {
    display: grid;
    grid-template-columns: 1fr 1fr auto;
    gap: 20px;
    align-items: end;
    
    .form-item {
      display: flex;
      flex-direction: column;
      gap: 8px;
      
      .form-label {
        font-size: 14px;
        font-weight: 500;
        color: #333;
        margin-bottom: 4px;
      }
    }
    
    .search-btn {
      min-width: 120px;
      height: 40px;
      background: linear-gradient(135deg, #1f4e79, #2c5aa0);
      border: none;
      border-radius: 8px;
      font-weight: 600;
      box-shadow: 0 4px 12px rgba(31, 78, 121, 0.3);
      transition: all 0.3s ease;
      
      &:hover:not(:disabled) {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(31, 78, 121, 0.4);
        background: linear-gradient(135deg, #2c5aa0, #4a90e2);
      }
      
      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
        transform: none;
        box-shadow: none;
      }
    }
  }
}

.quick-routes {
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid rgba(31, 78, 121, 0.1);
  
  .routes-header {
    margin-bottom: 12px;
    
    .routes-title {
      font-size: 14px;
      font-weight: 600;
      color: #333;
    }
  }
  
  .routes-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    
    .route-item {
      display: flex;
      align-items: center;
      gap: 6px;
      position: relative;
      
      .route-btn {
        background: white;
        border: 1px solid #d9d9d9;
        border-radius: 20px;
        color: #666;
        font-size: 13px;
        padding: 8px 16px;
        transition: all 0.3s ease;
        min-width: 150px;
        min-height: 48px; // 确保足够的高度
        
        .route-content {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 4px;
          width: 100%;
          
          .route-name {
            font-weight: 500;
            line-height: 1.2;
            text-align: center;
            word-break: keep-all;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 100%;
          }
          
          .route-stats {
            font-size: 11px;
            opacity: 0.8;
            font-weight: 400;
            white-space: nowrap;
            text-align: center;
            margin-top: 2px;
            
            &:contains("🔍") {
              color: #409eff;
            }
            
            &:contains("⭐") {
              color: #f7ba2a;
            }
          }
        }
        
        &:hover {
          border-color: #1f4e79;
          color: #1f4e79;
          background: rgba(31, 78, 121, 0.05);
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(31, 78, 121, 0.15);
        }
        
        &:active {
          transform: translateY(0);
          box-shadow: 0 2px 6px rgba(31, 78, 121, 0.2);
        }
      }
      
      .favorite-btn {
        min-width: 24px;
        width: 24px;
        height: 24px;
        padding: 0;
        border-radius: 50%;
        transition: all 0.3s ease;
        
        &:hover {
          transform: scale(1.1);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        }
        
        .el-icon {
          font-size: 12px;
        }
        
        // 收藏状态样式
        &.el-button--warning {
          background: #f7ba2a;
          border-color: #f7ba2a;
          color: white;
          
          &:hover, &:focus {
            background: #f7ba2a;
            border-color: #f7ba2a;
            color: white;
          }
        }
        
        // 未收藏状态样式
        &.el-button--default {
          background: white;
          border-color: #dcdfe6;
          color: #909399;
          
          &:hover, &:focus {
            background: #f5f7fa;
            border-color: #c0c4cc;
            color: #606266;
          }
        }
      }
    }
  }
}

/* 响应式设计 - 快捷查询 */
@media (max-width: 1200px) {
  .search-form .form-row {
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    
    .search-btn {
      grid-column: 1 / -1;
      justify-self: center;
      min-width: 160px;
    }
  }
}

@media (max-width: 768px) {
  .quick-search-section {
    margin: 20px 0;
    
    .quick-search-card {
      :deep(.el-card__body) {
        padding: 16px;
      }
    }
  }
  
  .search-form .form-row {
    grid-template-columns: 1fr;
    gap: 12px;
    
    .search-btn {
      grid-column: 1;
      width: 100%;
      min-width: auto;
    }
  }
  
  .quick-routes {
    margin-top: 16px;
    padding-top: 16px;
    
    .routes-list {
      gap: 6px;
      
      .route-item {
        gap: 4px;
        
        .route-btn {
          font-size: 12px;
          padding: 5px 12px;
        }
        
        .favorite-btn {
          min-width: 20px;
          width: 20px;
          height: 20px;
          
          .el-icon {
            font-size: 10px;
          }
        }
      }
    }
  }
}
</style>
